package handler

import (
    "fcs-api/src/app/model"
    "fcs-api/src/app/service/ksvc"
    "fcs-api/src/app/service/namespace"
    apierrors "k8s.io/apimachinery/pkg/api/errors"
    "net/http"
    "strings"

    "strconv"

    "git.inspur.com/x/common/i18n"
    "github.com/emicklei/go-restful"
    "k8s.io/apimachinery/pkg/util/rand"
)

func (api *APIHandler) handleCreateGroup(request *restful.Request, response *restful.Response) {
    logger.Debug("handleCreateGroup start.")
    fcClient, err := GetFcClient(api)
    if err != nil {
        _ = logger.Error("handleCreateGroup get cmanagerconfig error %v", err)
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.create")))
        return
    }
    group, err := ReadAndValidateGroup(request)
    if err != nil {
        _ = logger.Error("handleCreateGroup ReadAndValidateGroup error %v", err)
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.create")))
        return
    }
    logger.Debug("handleCreateGroup ReadEntity : %v", group)

    exist, err := model.CheckGroupExist(group.Creator, group.DisplayName)
    if err != nil {
        _ = logger.Error("handleCreateGroup CheckGroupExist error %v", err)
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.create")))
        return
    }
    if exist {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.name_dup")))
        return
    }

    group.Name = rand.String(10)
    ns := ksvc.GetGroupNs(group)
    if err := namespace.CreateNamespace(fcClient, ns); err != nil {
        _ = logger.Error("handleCreateGroup CreateNamespace err : %v", err)
        if strings.Contains(err.Error(), "already exists") {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.name_dup")))
            return
        } else {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.create")))
            return
        }
    }
    group, err = model.CreateGroup(group)
    if err != nil {
        _ = namespace.DeleteNamespace(fcClient, ns)
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.create")))
        return
    }
    //// 添加pod隔离，异步执行
    //go networkpolicy.CreateDefaultPolicy(fcClient, ns)
    //// 添加pod访问外网策略
    //go networkpolicy.CreateFunctionPublicPolicy(fcClient, ns)
    _ = response.WriteHeaderAndEntity(http.StatusOK, group)
}

func (api *APIHandler) handleGetGroupList(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetGroupList start.")
    var err error
    pageNoStr := request.QueryParameter("pageNo")
    pageSizeStr := request.QueryParameter("pageSize")
    name := request.QueryParameter("displayName")
    pageNo, pageSize := 1, 1000000
    if pageNoStr != "" || pageSizeStr != "" {
        pageNo, err = strconv.Atoi(pageNoStr)
        if err != nil {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.query_param")))
            return
        }
        pageSize, err = strconv.Atoi(pageSizeStr)
        if err != nil {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.query_param")))
            return
        }
    }

    user := currentUser(request)
    gp, err := model.GetGroupList(user, pageNo, pageSize, name)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.query")))
        return
    }
    if pageNoStr != "" || pageSizeStr != "" {
        _ = response.WriteHeaderAndEntity(http.StatusOK, gp)
        return
    }
    // api 网关调用接口获取全部数据...
    _ = response.WriteHeaderAndEntity(http.StatusOK, gp.Data)
}

func (api *APIHandler) handleGetGroupDetail(request *restful.Request, response *restful.Response) {
    logger.Debug("handleGetGroupDetail start.")
    groupId := request.PathParameter("groupId")
    group, err := model.GetGroupById(groupId)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.query_info")))
        return
    }
    _ = response.WriteHeaderAndEntity(http.StatusOK, group)
}

func (api *APIHandler) handleUpdateGroup(request *restful.Request, response *restful.Response) {
    logger.Debug("handleUpdateGroup start.")
    group := &model.Group{}
    group, err := ReadAndValidateGroup(request)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.update")))
        return
    }
    group.Id = request.PathParameter("groupId")
    group, err = model.UpdateGroup(group)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.update")))
        return
    }
    _ = response.WriteHeaderAndEntity(http.StatusOK, group)
}

func (api *APIHandler) handleDeleteGroup(request *restful.Request, response *restful.Response) {
    logger.Debug("handleDeleteGroup start.")
    groupId := request.PathParameter("groupId")
    user := currentUser(request)
    //检查分组下是否有函数
    funclistQ := &model.FunctionListQuery{GroupId: groupId, Creator: user.Id, AccountId: user.AccountId}
    funcInfoList, err := model.GetFuncInfoListByGroup(funclistQ)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete")))
        return
    }
    if len(funcInfoList) != 0 {
        logger.Debug("len(funcInfoList): ", len(funcInfoList))
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete_function")))
        return
    }

    fcClient, err := GetFcClient(api)
    if err != nil {
        _ = logger.Error("handleDeleteGroup get cmanagerconfig error %v", err)
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete")))
        return
    }
    group, err := model.GetGroupById(groupId)
    if err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete")))
        return
    }
    ns := ksvc.GetGroupNs(group)
    if err := namespace.DeleteNamespace(fcClient, ns); err != nil {
        // 当命名空间不存在的时候可以继续删除
        if !apierrors.IsNotFound(err) {
            handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete")))
            return
        }
    }
    if err := model.DeleteGroup(groupId); err != nil {
        handleInternalError(response, model.InternalServerError(model.TriggerError, i18n.GetMessage(request.Request, "fcs.group.delete")))
        return
    }
    deleteCode(group.A5tId, group.Name, "")
}

func (api *APIHandler) handleCheckGroupExist(request *restful.Request, response *restful.Response) {
    groupDisplayName := request.QueryParameter("groupDisplayName")
    user := currentUser(request)
    exist, err := model.CheckGroupExist(user.Id, groupDisplayName)
    if err != nil {
        _ = logger.Error("handleCheckGroupExist CheckGroupExist error %v", err)
    }
    _ = response.WriteHeaderAndEntity(http.StatusOK, map[string]interface{}{"exist": exist})
}
